package top.xxyu.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.xxyu.dao.FileInfoDao;
import top.xxyu.dao.ServerLogDao;
import top.xxyu.dao.WindowsServerDao;
import top.xxyu.entity.FileInfo;
import top.xxyu.entity.ServerLog;
import top.xxyu.entity.WindowsServer;
import top.xxyu.service.WindowsServerService;
import top.xxyu.utils.SSHGanymedUtil;
import top.xxyu.utils.SftpClient;

import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class WindowsServerServiceimpl implements WindowsServerService {

    private Logger log = LoggerFactory.getLogger(WindowsServerService.class);

    @Autowired
    private WindowsServerDao windowsServerDao;
    @Autowired
    private ServerLogDao serverLogDao;
    @Autowired
    private FileInfoDao fileInfoDao;

    @Override
    public String updatePatch(List<WindowsServer> datas) {
        List<FileInfo> filess = fileInfoDao.findAll();
        FileInfo fileInfo = filess.get(0);
        String path = fileInfo.getPath();

        WindowsServer windowsServer = datas.get(0);
        if(Objects.isNull(windowsServer.getTomcatPatch())){
            return "false";
        }
        String localFile = path.replaceAll(".zip", "")+"";
//        SSHGanymedUtil sshGanymedUtil = getSshGanymedUtil(windowsServer);

        SftpClient sftpClient = new SftpClient();
        sftpClient.setHost(windowsServer.getIp());
        sftpClient.setUsername(windowsServer.getUserName());
        sftpClient.setPassword(windowsServer.getPassWord());
        String id_rsa_2048 = Thread.currentThread().getContextClassLoader().getResource("id_rsa_2048-116").getPath();
        sftpClient.setPrivateKey(id_rsa_2048);
        sftpClient.connect();
        try {
            WindowsServer one = windowsServerDao.getOne(windowsServer.getId());
            one.setPatchStatus("代码部署中");
            windowsServerDao.saveAndFlush(one);
            sftpClient.transferDirectory(localFile, windowsServer.getTomcatPatch());
            one.setPatchStatus("代码部署完成"+ DateFormat.getDateTimeInstance().format(new Date()));
            windowsServerDao.saveAndFlush(one);
            sftpClient.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            if(sftpClient.isConnected()){
                sftpClient.disconnect();
            }
        }
        return "success";
    }


    @Override
    public String doStart(List<WindowsServer> datas) {

        WindowsServer windowsServer = datas.get(0);
        String id_rsa111 = Thread.currentThread().getContextClassLoader().getResource("id_rsa_2048-116").getPath();
        File file = new File(id_rsa111);
        SSHGanymedUtil sshGanymedUtil = new SSHGanymedUtil(windowsServer.getIp()
                , 22, windowsServer.getUserName(),
                windowsServer.getPassWord());
        String result="";
        try {
            boolean b = sshGanymedUtil.loginPuk();
            if(!b){
                return "";
            }
            String fol = " net start "+windowsServer.getTomcatName();
            result = sshGanymedUtil.execCommand(fol);
            sshGanymedUtil.closeConnection();
            log.info(result);
            insetLog(windowsServer, result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void insetLog(WindowsServer windowsServer, String result) {
        ServerLog logg = new ServerLog();
        logg.setId(UUID.randomUUID().toString());
        logg.setContent(result);
        logg.setTomcatName(windowsServer.getTomcatName());
        logg.setIp(windowsServer.getIp());
//        serverLogDao.save(logg);
    }

    @Override
    public String doStop(List<WindowsServer> datas) {
        WindowsServer windowsServer = datas.get(0);
        SSHGanymedUtil sshGanymedUtil = getSshGanymedUtil(windowsServer);
        String result="";
        try {
            boolean b = sshGanymedUtil.loginPuk();
            if(!b){
                return "";
            }
            String fol = " net stop "+windowsServer.getTomcatName();
            result = sshGanymedUtil.execCommand(fol);
            sshGanymedUtil.closeConnection();
            windowsServer.setStatus(result);
            windowsServerDao.save(windowsServer);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private SSHGanymedUtil getSshGanymedUtil(WindowsServer windowsServer) {
        String id_rsa111 = Thread.currentThread().getContextClassLoader().getResource("id_rsa_2048-116").getPath();
        File file = new File(id_rsa111);
        return new SSHGanymedUtil(windowsServer.getIp()
                , 22, windowsServer.getUserName(),
                windowsServer.getPassWord());
    }


    private String formatStr( String str){
        if(str.contains("RUNNING")){
            return "RUNNING";
        } else if(str.contains("STOP_PENDING")){
            return "STOP_PENDING";
        } else if(str.contains("STOPPED")){
            return "STOPPED";
        } else if(str.contains("RUNNING")){
            return "RUNNING";
        } else if(str.contains("RUNNING")){
            return "RUNNING";
        }
        return str;
    }


    @Override
    public String executeKill(WindowsServer windowsServer) {
        SSHGanymedUtil sshGanymedUtil = getSshGanymedUtil(windowsServer);
        boolean b = sshGanymedUtil.loginPuk();
            if(!b){
                return "";
            }
        String commond = "netstat -ano | findstr "+ windowsServer.getTomcatPort();
        String result = sshGanymedUtil.execCommand(commond);
        if(!Objects.isNull(result)){
            String[] tcps = result.split("TCP");
            System.out.println(result);
            for (int i = 0; i < tcps.length; i++) {
                System.out.println(tcps[i]);
                if(tcps[i].contains("0.0.0.0:"+windowsServer.getTomcatPort()+" ")){
                    String pid = tcps[i].substring(tcps[i].length() - 7);
                    System.out.println(tcps[i].substring(tcps[i].length() -7));
                    if(pid.trim().equals(0)){
                        continue;
                    }
                    sshGanymedUtil.execCommand( "taskkill /f /pid "+pid);
                }
            }
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        sshGanymedUtil.closeConnection();
        String s = queryStatus(windowsServer);

        log.info(s);
        return s;
    }
    @Override
    public String queryStatus(WindowsServer windowsServer){
        String result = null;
        try {
            SSHGanymedUtil sshGanymedUtil = getSshGanymedUtil(windowsServer);
            boolean b = sshGanymedUtil.loginPuk();
            if(!b){
                return "";
            }
            String commond = "sc query "+ windowsServer.getTomcatName();
            result = sshGanymedUtil.execCommand(commond);
            result = formatStr(result);
            windowsServer.setStatus(result);
            sshGanymedUtil.closeConnection();
        } catch (Exception e) {
            e.printStackTrace();
            windowsServer.setStatus(e.toString());
        } finally {

        }
        windowsServerDao.save(windowsServer);
        log.info(result);
        insetLog(windowsServer, result);
        return result;
    }

//    /**
//     * 传输整个目录
//     *
//     * @param localresultectory
//     * @param remoteTargetresultectory
//     * @throws IOException
//     */
//    public void transferresultectory(String localresultectory, String remoteTargetresultectory) throws IOException {
//        File result = new File(localresultectory);
//        if (!result.isresultectory()) {
//            throw new RuntimeException(localresultectory + " is not resultectory");
//        }
//
//        String[] files = result.list();
//        for (String file : files) {
//            if (file.startsWith(".")) {
//                continue;
//            }
//            String fullName = localresultectory + "/" + file;
//            if (new File(fullName).isresultectory()) {
//                String rresult = remoteTargetresultectory + "/" + file;
//                execCommand("mkresult -p " + remoteTargetresultectory + "/" + file);
//                transferresultectory(fullName, rresult);
//            } else {
//                transferFile(fullName, remoteTargetresultectory);
//            }
//        }
//
//    }
}
